/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sita.friend.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easemob.util.EMLog;
import com.sita.bike.R;
import com.sita.bike.model.EaseUser2;
import com.sita.friend.FriendHelper;
import com.sita.friend.FriendHelper.DataSyncListener;
import com.sita.friend.db.InviteMessgeDao;
import com.sita.friend.event.AcceptFriendEvent;
import com.sita.friend.event.AddFriendEvent;
import com.sita.friend.ui.activity.NewFriendsMsgActivity;
import com.sita.friend.ui.widget.EaseContactList;
import com.sita.friend.utils.MessageUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import de.greenrobot.event.EventBus;

/**
 * 联系人列表页
 */
public class FriendListFragment extends Fragment {

    private static final String TAG = FriendListFragment.class.getSimpleName();
    private ContactSyncListener contactSyncListener;
    private BlackListSyncListener blackListSyncListener;
    private ContactInfoSyncListener contactInfoSyncListener;
    private View loadingView;
    private InviteMessgeDao inviteMessgeDao;
    protected List<String> blackList;
    protected ListView listView;
    protected FrameLayout contentContainer;
    protected InputMethodManager inputMethodManager;
    private View root;
    private Map<String, EaseUser2> contactsMap;
    protected EaseContactList contactListLayout;
    @Bind(R.id.img_back)
    public ImageView img_back;
    private TextView tvFriendUnreadMessageNumber;

    public FriendListFragment() {
    }
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.inputMethodManager = (InputMethodManager) this.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        this.initView();
        this.setUpView();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return root = inflater.inflate(R.layout.friend_fragment_contact_list, container, false);
    }

    protected void initView() {
        HeaderItemClickListener clickListener = new HeaderItemClickListener();
        RelativeLayout newfriend = (RelativeLayout) root.findViewById(R.id.rl_friend_new);
        newfriend.setOnClickListener(clickListener);
        ImageView imgBack = (ImageView) root.findViewById(R.id.img_back);
        imgBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
//        ImageView img_add_friend = (ImageView)root.findViewById(R.id.img_add_friend) ;
//        img_add_friend.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(getActivity(), FriendAddUserActivity.class));
//            }
//        });

        contactListLayout = (EaseContactList) getView().findViewById(R.id.contact_list);
        listView = contactListLayout.getListView();

//        headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
//        headerView.findViewById(R.id.chat_room_item).setOnClickListener(clickListener);
//        headerView.findViewById(R.id.robot_item).setOnClickListener(clickListener);
//        listView = (ListView) root.findViewById(R.id.contact_list);
//        listView = contactListLayout.getListView();
//        //添加headerview
//        listView.addHeaderView(headerView);
        //添加正在加载数据提示的loading view
//        loadingView = LayoutInflater.from(getActivity()).inflate(R.layout.em_layout_loading_data, null);
//        contentContainer = (FrameLayout) root.findViewById(R.id.content_container);
//        contentContainer.addView(loadingView);
//        //注册上下文菜单
//        registerForContextMenu(listView);
        tvFriendUnreadMessageNumber = (TextView) root.findViewById(R.id.friend_unread_msg_number);
        tvFriendUnreadMessageNumber.setVisibility(View.INVISIBLE);
    }


    public void refreshUnreadFriendInviteMessage() {
        if (tvFriendUnreadMessageNumber == null) {
            return;
        }
        int count = MessageUtils.getUnreadInviteMessageCount();
        if (count > 0) {
            tvFriendUnreadMessageNumber.setText(String.valueOf(count));
            tvFriendUnreadMessageNumber.setVisibility(View.VISIBLE);
        }else {
            tvFriendUnreadMessageNumber.setText(String.valueOf(count));
            tvFriendUnreadMessageNumber.setVisibility(View.INVISIBLE);
        }
    }

    public void setContactsMap(Map<String, EaseUser2> contactsMap) {
        this.contactsMap = contactsMap;
    }

    protected List<EaseUser2> contactList;

    /**
     * 获取联系人列表，并过滤掉黑名单和排序
     */
    protected void getContactList() {
        contactList.clear();
        synchronized (contactList) {
            //获取联系人列表
            if (contactsMap == null) {
                return;
            }
            Iterator<Map.Entry<String, EaseUser2>> iterator = contactsMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, EaseUser2> entry = iterator.next();
                //兼容以前的通讯录里的已有的数据显示，加上此判断，如果是新集成的可以去掉此判断
                if (!entry.getKey().equals("item_new_friends")
                        && !entry.getKey().equals("item_groups")
                        && !entry.getKey().equals("item_chatroom")
                        && !entry.getKey().equals("item_robots")) {
//                    if(!blackList.contains(entry.getKey())){
                    //不显示黑名单中的用户
                    EaseUser2 user = entry.getValue();
//                        EaseCommonUtils.setUserInitialLetter(user);
                    contactList.add(user);
//                    }
                }
            }
//            // 排序
//            Collections.sort(contactList, new Comparator<EaseUser>() {
//
//                @Override
//                public int compare(EaseUser lhs, EaseUser rhs) {
//                    if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
//                        return lhs.getNick().compareTo(rhs.getNick());
//                    } else {
//                        if ("#".equals(lhs.getInitialLetter())) {
//                            return 1;
//                        } else if ("#".equals(rhs.getInitialLetter())) {
//                            return -1;
//                        }
//                        return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
//                    }
//
//                }
//            });
        }

    }

    protected void setUpView2() {
//        EMChatManager.getInstance().addConnectionListener(connectionListener);

//        //黑名单列表
//        blackList = EMContactManager.getInstance().getBlackListUsernames();
        contactList = new ArrayList<EaseUser2>();
        // 获取设置contactlist
        getContactList();
        //init list
        contactListLayout.init(contactList);

//        if(listItemClickListener != null){
//            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                    EaseUser user = (EaseUser)listView.getItemAtPosition(position);
//                    listItemClickListener.onListItemClicked(user);
////                    itemClickLaunchIntent.putExtra(EaseConstant.USER_ID, username);
//                }
//            });
//        }

//        query.addTextChangedListener(new TextWatcher() {
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                contactListLayout.filter(s);
//                if (s.length() > 0) {
//                    clearSearch.setVisibility(View.VISIBLE);
//                } else {
//                    clearSearch.setVisibility(View.INVISIBLE);
//
//                }
//            }
//
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            public void afterTextChanged(Editable s) {
//            }
//        });
//        clearSearch.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                query.getText().clear();
//                hideSoftKeyboard();
//            }
//        });

        listView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 隐藏软键盘
                hideSoftKeyboard();
                return false;
            }
        });

    }

    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void setUpView() {

        //设置联系人数据
        setContactsMap(FriendHelper.getInstance().getContactList());

        setUpView2();
//        {
//
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                // TODO: 2015/12/13
//                String username = ((EaseUser)listView.getItemAtPosition(position)).getUsername();
//                // demo中直接进入聊天页面，实际一般是进入用户详情页
//                startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", username));
//            }
//        });


        contactSyncListener = new ContactSyncListener();
        FriendHelper.getInstance().addSyncContactListener(contactSyncListener);

        blackListSyncListener = new BlackListSyncListener();
        FriendHelper.getInstance().addSyncBlackListListener(blackListSyncListener);

//        contactInfoSyncListener = new ContactInfoSyncListener();
//        FriendHelper.getInstance().getUserProfileManager().addSyncContactInfoListener(contactInfoSyncListener);

//        if (!FriendHelper.getInstance().isContactsSyncedWithServer()) {
//            loadingView.setVisibility(View.VISIBLE);
//        } else {
//            loadingView.setVisibility(View.GONE);
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (contactSyncListener != null) {
            FriendHelper.getInstance().removeSyncContactListener(contactSyncListener);
            contactSyncListener = null;
        }

        if (blackListSyncListener != null) {
            FriendHelper.getInstance().removeSyncBlackListListener(blackListSyncListener);
        }

//        if(contactInfoSyncListener != null){
//            FriendHelper.getInstance().getUserProfileManager().removeSyncContactInfoListener(contactInfoSyncListener);
//        }
    }


    protected class HeaderItemClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rl_friend_new:
                    // TODO: 2015/12/15

                    // 清所有的好友通知
                    MessageUtils.resetUnreadInviteMessageCount();
                    // 进入申请与通知页面
                    startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class));
                    break;

                default:
                    break;
            }
        }

    }



    class ContactSyncListener implements DataSyncListener {
        @Override
        public void onSyncComplete(final boolean success) {
//            EMLog.d(TAG, "on contact list sync success:" + success);
//            getActivity().runOnUiThread(new Runnable() {
//                public void run() {
//                    getActivity().runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            if (success) {
//                                loadingView.setVisibility(View.GONE);
//                                refreshUnreadFriendInviteMessage();
//                            } else {
//                                String s1 = getResources().getString(R.string.get_failed_please_check);
//                                Toast.makeText(getActivity(), s1, Toast.LENGTH_LONG).show();
//                                loadingView.setVisibility(View.GONE);
//                            }
//                        }
//
//                    });
//                }
//            });
        }
    }

    class BlackListSyncListener implements DataSyncListener {

        @Override
        public void onSyncComplete(boolean success) {
//            getActivity().runOnUiThread(new Runnable() {
//
//                @Override
//                public void run() {
//                    blackList = EMContactManager.getInstance().getBlackListUsernames();
//                    refreshUnreadFriendInviteMessage();
//                }
//
//            });
        }

    }

    class ContactInfoSyncListener implements DataSyncListener {

        @Override
        public void onSyncComplete(final boolean success) {
            EMLog.d(TAG, "on contactinfo list sync success:" + success);
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    loadingView.setVisibility(View.GONE);
                    if (success) {
                        refreshUnreadFriendInviteMessage();
                    }
                }
            });
        }

    }

    @Override
    public void onResume() {
        // TODO: 2016/3/4 no need to reset up view every time
        setUpView();
        refreshUnreadFriendInviteMessage();
        super.onResume();
    }

    public void onEventMainThread(AcceptFriendEvent event) {
        refreshUnreadFriendInviteMessage();
        setUpView();
    }

    public void onEventMainThread(AddFriendEvent event) {
        Log.d("ReceiveMessage", "OnEvent收到了好友消息：" + event.fromUserId);
        refreshUnreadFriendInviteMessage();
    }

    @Override
    public void onStart() {
        EventBus.getDefault().register(this);
        super.onStart();
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
}
